//
//  BDDiscoverViewController.m
//  BadBoy
//
//  Created by wen on 2017/3/10.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDDiscoverViewController.h"
#import <AMap2DMap-NO-IDFA/MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <CoreLocation/CoreLocation.h>
#import "BDDiscoverLeftTableViewCell.h"
#import "BDUserModel.h"
#import "BDDiscoverShopModel.h"
#import "BDShopInfoDeatilViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "BDDiscoverAnnotationView.h"
#import "BDDiscoverSearchViewController.h"
#import "BDLocationServer.h"
#import "JSDropDownMenu.h"
#import <UIButton+WebCache.h>
#import "CallExternalProcessBehavior.h"
#import "BDCityInfo.h"
#import "BDButtonAlert.h"
#import "BDPostHelper.h"

#define  Width 50
#define kLeftViewLitWidth  (kBDScreenWidth/3.0*2+Width)

typedef NS_ENUM(NSUInteger, LeftTableScrollStep) {
    LeftTableScrollStepOne,
    LeftTableScrollStepOneHalf,
    LeftTableScrollStepTwo,
    LeftTableScrollStepTwoHalf,
    LeftTableScrollStepThree
};

@interface BDDiscoverViewController ()<MAMapViewDelegate, AMapLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, UITextFieldDelegate, JSDropDownMenuDataSource, JSDropDownMenuDelegate>
{
    NSString *district_id;
    BOOL isFirst;
    
    BOOL isUseSearchUrl;
    
    NSMutableArray *_data1;
    NSMutableArray *_data2;
    NSMutableArray *_data3;
    
    NSInteger _currentData1LeftIndex;
    NSInteger _currentData1Index;
    NSInteger _currentData2Index;
    NSInteger _currentData3Index;
    
    NSString *currentCity;
    BOOL hasRefresh;
}
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) UIButton *fangdaBtn;
@property (nonatomic, strong) UIButton *suoxiaoBtn;
@property (nonatomic, strong) UIButton *gpsButton;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *leftView;
@property (nonatomic, strong) NSMutableArray *datasource;

@property (nonatomic, strong) NSMutableArray *annotations;//地图上的部分

@property (nonatomic, strong) UIView *bkView;

@property (nonatomic, assign) LeftTableScrollStep scrollStep;

@property (nonatomic, strong) JSDropDownMenu *dropMenu;
@property (nonatomic, strong) UIView *locationView;

@end

@implementation BDDiscoverViewController
/*
 1.左侧tableviewcell点击标题和图片才进入详情页，否则不变
 2.气泡只有点击标题的时候才进入详情页，否则不变
 3.修改气泡字体大小；；；
 4.在回到原地的时候不刷新数据；；；
 5.根据类型区分气泡颜色
 6.显示用户定位精度
 */

static CGFloat leftSide = 25;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageSize = @"100";
}

//http://api.beboy.me/api/shops?page=1&size=100&order=1&user_lng=113.332755&user_lat=23.132751&lng=120.153566&lat=30.287460&lng_radius=0.014010&lat_radius=0.019453&type=4

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    NSString *lastCity = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastCity"];
    if (![currentCity isEqualToString:lastCity]) {
        [self startLocation];
        currentCity = lastCity;
    }
    
    NSArray *typeArray = @[ASLocalizedString(@"全部"), ASLocalizedString(@"水疗"), @"KTV", ASLocalizedString(@"夜总会"), ASLocalizedString(@"酒吧"), ASLocalizedString(@"沐足"), ASLocalizedString(@"其他")];
    NSString *currentType = [[NSUserDefaults standardUserDefaults] objectForKey:@"shopAndPostType"];
    _currentData2Index = [typeArray indexOfObject:currentType];
    
    BDCityInfo *cityInfo = [BDCityInfo getCityWithName:currentCity type:BDCityTypeCity];
    NSArray *districArray = [BDCityInfo getCityArrayWithParentId:cityInfo.infoID];
    NSMutableArray *districNameArray = [NSMutableArray array];
    for (BDCityInfo *districInfo in districArray) {
        [districNameArray addObject:districInfo.name];
    }
    
    _data1 = [NSMutableArray arrayWithObjects:@{@"title":ASLocalizedString(@"距离"), @"data":@[ASLocalizedString(@"附近"),@"1 km",@"3 km",@"5 km",@"10 km"]},
              @{@"title":ASLocalizedString(@"区域"), @"data":districNameArray}, nil];
    _data2 = [NSMutableArray arrayWithObjects:ASLocalizedString(@"全部"), ASLocalizedString(@"水疗"), @"KTV", ASLocalizedString(@"夜总会"), ASLocalizedString(@"酒吧"), ASLocalizedString(@"沐足"), ASLocalizedString(@"其他"), nil];
    _data3 = [NSMutableArray arrayWithObjects:ASLocalizedString(@"智能排序"), ASLocalizedString(@"评价最高"), ASLocalizedString(@"距离最近"), ASLocalizedString(@"价格最低"), nil];
    if (isFirst == NO) {
        [self layoutViews];
        [self bindRAC];
        isFirst = YES;
    }else{
        [self.dropMenu removeFromSuperview];
        self.dropMenu = nil;
        [self.view addSubview:self.dropMenu];
        if (self.scrollStep == LeftTableScrollStepThree) {
            self.dropMenu.top = kBDTopHeight;
        }else{
            self.dropMenu.bottom = kBDTopHeight;
        }
        self.startPage = @"1";
    }
    [self requestDatasource];
}

- (void)startLocation{
    self.startPage = @"1";
    self.isEnd = NO;
    BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
    CLLocationCoordinate2D coordinate = [BDLocationServer getLastCoordinate];
    if (locationModel != nil) {
        self.mapView.centerCoordinate = CLLocationCoordinate2DMake(coordinate.latitude, coordinate.longitude);
//        [self requestDatasource];
    }
}

- (void)requestDatasource{
    NSString *city_id = [BDLocationServer getCityIdWithCityName:[[NSUserDefaults standardUserDefaults] objectForKey:@"lastCity"] cityType:BDCityTypeCity];
    NSString *url = nil;
    BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
    double userLongitude = self.mapView.userLocation.location.coordinate.longitude == 0 ? locationModel.longitude : self.mapView.userLocation.location.coordinate.longitude;
    double userLatitude = self.mapView.userLocation.location.coordinate.latitude == 0 ? locationModel.latitude : self.mapView.userLocation.location.coordinate.latitude;
    // BDLog(ASLocalizedString(@"中心点：%f %f"), self.mapView.region.center.longitude, self.mapView.region.center.latitude);
    NSString *typeString = _data2[_currentData2Index];
    NSInteger typeIndex = [BDButtonAlert getTypeidWitTypeString:typeString];
    if (self.scrollStep != LeftTableScrollStepThree) {
        isUseSearchUrl = NO;
        url = [NSString stringWithFormat:@"%@shops?page=%@&size=%@&order=1&user_lng=%f&user_lat=%f&lng=%f&lat=%f&lng_radius=%f&lat_radius=%f&user_city_id=%@", KBDBaseURL, self.startPage, self.pageSize, userLongitude, userLatitude, self.mapView.region.center.longitude, self.mapView.region.center.latitude, self.mapView.region.span.longitudeDelta / 2.0, self.mapView.region.span.latitudeDelta / 2.0, city_id];
    }else{
        isUseSearchUrl = YES;
//        CLLocationCoordinate2D coordinate = [BDLocationServer getLastCoordinate];
        
        url = [NSString stringWithFormat:@"%@shops?page=%@&size=%@&order=%zd&user_lng=%f&user_lat=%f&city_id=%@&user_city_id=%@", KBDBaseURL, self.startPage, self.pageSize, _currentData3Index + 1, userLongitude, userLatitude, city_id, city_id];
        
        //第一部分：区域和距离
        if (_currentData1LeftIndex == 1) {
            //区域
            NSString *dictrictName = [[_data1[1] objectForKey:@"data"] objectAtIndex:_currentData1Index];
            NSString *dictrict_id = [BDLocationServer getCityIdWithCityName:dictrictName cityType:BDCityTypeDistrict];
            url = [url stringByAppendingString:[NSString stringWithFormat:@"&district_id=%@", dictrict_id]];
        }else{
            //距离
            NSArray *arr = @[@(1), @(3), @(5), @(10)];
            if (_currentData1Index > 0) {
                url = [url stringByAppendingString:[NSString stringWithFormat:@"&distance=%@", arr[_currentData1Index - 1]]];
            }
        }
        //第二部分：类型
//        if (_currentData2Index != 0) {
            url = [url stringByAppendingString:[NSString stringWithFormat:@"&type=%zd", typeIndex]];
//        }
    }
    [self requestWithUrl:url];
}

- (void)requestWithUrl:(NSString *)url{
    
    NSString *headValid = [BDUserModel getHeaderValidation];
    // BDLog(ASLocalizedString(@"当前发现的url是：%@"), url);
    RACCommand *command = [BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES];
    RACSignal *signal = [command execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        NSArray *array = x[@"list"];
        self.datasource = [BDDiscoverShopModel mj_objectArrayWithKeyValuesArray:array];

        //获取当前地图上商家坐标
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.scrollStep != LeftTableScrollStepThree) {
                [self.mapView removeAnnotations:self.annotations];
                [self getBusLocation];
                //添加大头针
                [self.mapView addAnnotations:self.annotations];
            }
            
            //刷新tableView
            [self.tableView.mj_footer endRefreshing];
            [self.tableView.mj_header endRefreshing];
            [self.tableView reloadData];
            
        });
        self.isEnd = [x[@"is_end"] boolValue];
        self.startPage = x[@"next_page"];
        if (self.isEnd == YES) {
            self.tableView.mj_footer = nil;
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 40)];
            label.textColor = [UIColor colorWithHexString:@"#767676"];
            label.font = [UIFont systemFontOfSize:14];
            label.textAlignment = NSTextAlignmentCenter;
            label.backgroundColor = [UIColor clearColor];
            label.text = ASLocalizedString(@"以上是所有内容");
            self.tableView.tableFooterView = label;
        }else{
            self.tableView.tableFooterView = nil;
            self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                [self requestDatasource];
            }];
        }
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        // BDLog(ASLocalizedString(@"请求数据失败, error:%@"), error);
    }];
}

- (void)getBusLocation{
    [self.annotations removeAllObjects];
    for (int i = 0; i < self.datasource.count; i++) {
        BDDiscoverShopModel *shopModel = self.datasource[i];
        MAPointAnnotation *a1 = [[MAPointAnnotation alloc] init];
        a1.coordinate = CLLocationCoordinate2DMake(shopModel.latitude, shopModel.longitude);
        a1.title = shopModel.title;
        a1.subtitle = shopModel.address;
        
        [self.annotations addObject:a1];
    }
}

- (void)layoutViews{
    
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 273 / 375.0 * kBDScreenWidth, 30)];
    textField.backgroundColor = [UIColor colorWithHexString:@"#555555"];
    textField.tintColor = [UIColor colorWithHexString:@"#bbbbbb"];
    textField.font = [UIFont systemFontOfSize:13];
    textField.placeholder = ASLocalizedString(@"搜索商家");
    textField.textColor = [UIColor whiteColor];
    textField.delegate = self;
    textField.layer.masksToBounds = YES;
    textField.layer.cornerRadius = 5;
    
    [textField setValue:[UIColor colorWithHexString:@"#bbbbbb"] forKeyPath:@"_placeholderLabel.textColor"];
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 35, 30)];
    leftView.backgroundColor = [UIColor clearColor];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    imageView.image = [UIImage imageNamed:@"sousuo"];
    [leftView addSubview:imageView];
    imageView.right = leftView.width - 5;
    imageView.centerY = leftView.height / 2.0;
    textField.leftView = leftView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    self.navigationItem.titleView = textField;
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self.view addSubview:self.mapView];
    
    UIView *zoomPannelView = [self makeZoomPannelView];
    zoomPannelView.right = kBDScreenWidth - 10;
    zoomPannelView.bottom = kBDScreenHeight - kBDTabBarHeight - 10;
    [self.view addSubview:zoomPannelView];
    
    [self.view addSubview:self.gpsButton];
    [self.view addSubview:self.leftView];
    self.leftView.left = 0;
    self.leftView.width = kBDScreenWidth + leftSide;
    self.tableView.width = self.leftView.width - leftSide;
    
    [self.view addSubview:self.dropMenu];
    self.dropMenu.top = kBDTopHeight;
    
    self.tableView.top = self.dropMenu.bottom - kBDTopHeight;
    
    self.scrollStep = LeftTableScrollStepThree;
    self.rightButton.selected = YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    BDDiscoverSearchViewController *searchVC = [[BDDiscoverSearchViewController alloc] init];
    searchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
    return NO;
}

- (void)bindRAC{
    [[self.rightButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self mapAndListChange];
    }];
    
    [[self.fangdaBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        CGFloat oldZoom = self.mapView.zoomLevel;
        [self.mapView setZoomLevel:(oldZoom + 1) animated:YES];
        self.startPage = @"1";
        [self requestDatasource];
    }];
    
    [[self.suoxiaoBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        CGFloat oldZoom = self.mapView.zoomLevel;
        [self.mapView setZoomLevel:(oldZoom - 1) animated:YES];
        self.startPage = @"1";
        [self requestDatasource];
    }];
    
    [[self.gpsButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if(self.mapView.userLocation.updating && self.mapView.userLocation.location) {
            BOOL needRefresh = NO;
            if (self.mapView.userLocation.location.coordinate.latitude != self.mapView.centerCoordinate.latitude || self.mapView.userLocation.location.coordinate.longitude != self.mapView.centerCoordinate.longitude) {
                needRefresh = YES;
            }
            [self.mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate animated:YES];
            if (needRefresh == YES) {
                self.startPage = @"1";
                
                NSString *url = [NSString stringWithFormat:@"%@shops?page=%@&size=%@&order=1&user_lng=%f&user_lat=%f&lng=%f&lat=%f&lng_radius=%f&lat_radius=%f", KBDBaseURL, self.startPage, self.pageSize, self.mapView.userLocation.location.coordinate.longitude, self.mapView.userLocation.location.coordinate.latitude, self.mapView.userLocation.location.coordinate.longitude, self.mapView.userLocation.location.coordinate.latitude, self.mapView.region.span.longitudeDelta / 2.0, self.mapView.region.span.latitudeDelta / 2.0];
                
                [self requestWithUrl:url];
            }
        }
    }];
    
    [RACObserve(self.leftView, right) subscribeNext:^(id  _Nullable x) {
        CGFloat curRight = [x floatValue];
        if (curRight == leftSide) {
            [self.view sendSubviewToBack:self.bkView];
        }else{
            [self.view bringSubviewToFront:self.bkView];
            [self.view bringSubviewToFront:self.leftView];
            [self.view bringSubviewToFront:self.locationView];
            [self.view bringSubviewToFront:self.dropMenu];
        }
        self.bkView.alpha = (curRight - leftSide) / 1.0 / self.tableView.width;
//        // BDLog(ASLocalizedString(@"当前背景的透明度：%.2f"), self.bkView.alpha);
    }];
}

- (void)setScrollStep:(LeftTableScrollStep)scrollStep{
    if (_scrollStep != scrollStep) {
        //上一次用的地图url，并且这一次是3，那么必然请求数据
        //上一次用的搜索url，并且这一次不是3和2.5，那么也必然请求数据，其余情况不请求
        BOOL flag1 = isUseSearchUrl == NO && scrollStep == LeftTableScrollStepThree;
        BOOL flag2 = isUseSearchUrl == YES && scrollStep < LeftTableScrollStepTwoHalf;
        
        if (flag1 || flag2) {
            self.startPage = @"1";
            _scrollStep = scrollStep;
            [self requestDatasource];
        }else{
            _scrollStep = scrollStep;
        }
    }
}

#pragma mark -----------------------有关tableView滑动-------------------------------
- (void)mapAndListChange{
    self.view.userInteractionEnabled = NO;
    if (self.dropMenu.bottom != kBDTopHeight) {
        [self.dropMenu shouqiTableView];
    }
    if (self.tableView.width == kBDScreenWidth) {
        [UIView animateWithDuration:0.3 animations:^{
            self.leftView.width = kLeftViewLitWidth;
            self.leftView.right = leftSide;
            self.tableView.width = kLeftViewLitWidth - leftSide;
            self.bkView.alpha = 0;
        } completion:^(BOOL finished) {
            self.view.userInteractionEnabled = YES;
            [self.view sendSubviewToBack:self.bkView];
            self.rightButton.selected = NO;
            self.scrollStep = LeftTableScrollStepOne;
            if (self.dropMenu.bottom != kBDTopHeight) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.dropMenu.bottom = kBDTopHeight;
                    self.tableView.top = self.dropMenu.bottom - kBDTopHeight;
                } completion:^(BOOL finished) {

                }];
            }
        }];
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            self.leftView.left = 0;
            [self.view bringSubviewToFront:self.bkView];
            [self.view bringSubviewToFront:self.leftView];
//            [self.view bringSubviewToFront:self.locationView];
            [self.view bringSubviewToFront:self.dropMenu];
            self.bkView.alpha = 1;
            self.leftView.width = kBDScreenWidth + leftSide;
            self.tableView.width = kBDScreenWidth;
        } completion:^(BOOL finished) {
            self.view.userInteractionEnabled = YES;
            self.rightButton.selected = YES;
            self.scrollStep = LeftTableScrollStepThree;
            if (self.dropMenu.top != kBDTopHeight) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.dropMenu.top = kBDTopHeight;
                    self.tableView.top = self.dropMenu.bottom - kBDTopHeight;
                } completion:^(BOOL finished) {
                    
                }];
            }
        }];
    }
}

- (void)startScroll{
    self.view.userInteractionEnabled = NO;
    if (self.dropMenu.bottom != kBDTopHeight) {
        [self.dropMenu shouqiTableView];
    }
    if (self.leftView.right == leftSide) {
        [UIView animateWithDuration:0.3 animations:^{
            self.leftView.left = 0;
            [self.view bringSubviewToFront:self.bkView];
            [self.view bringSubviewToFront:self.leftView];
//            [self.view bringSubviewToFront:self.locationView];
            [self.view bringSubviewToFront:self.dropMenu];
            self.bkView.alpha = 1;
            self.leftView.width = kLeftViewLitWidth;
            self.tableView.width = self.leftView.width - leftSide;
        } completion:^(BOOL finished) {
            self.view.userInteractionEnabled = YES;
            self.rightButton.selected = NO;
            self.scrollStep = LeftTableScrollStepTwo;
        }];
    }else {
        [UIView animateWithDuration:0.3 animations:^{
            self.leftView.right = leftSide;
            self.bkView.alpha = 0;
        } completion:^(BOOL finished) {
            self.view.userInteractionEnabled = YES;
            [self.view sendSubviewToBack:self.bkView];
            self.rightButton.selected = NO;
            self.scrollStep = LeftTableScrollStepOne;
            if (self.dropMenu.bottom != kBDTopHeight) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.dropMenu.bottom = kBDTopHeight;
//                    self.dropMenu.bottom = self.locationView.top;
                    self.tableView.top = self.dropMenu.bottom - kBDTopHeight;
                } completion:^(BOOL finished) {
                    
                }];
            }
        }];
    }
}

- (void)endScroll{
    //结束拖拽的时候，需要判断当前位置，是在什么地方,如果是在1、2状态的中间，那么就执行第一种方案，如果是在2、3的中间，那么就执行第二种方案
    self.view.userInteractionEnabled = NO;
    if (self.dropMenu.bottom != kBDTopHeight) {
        [self.dropMenu shouqiTableView];
    }
    CGFloat mid1 = (self.leftView.width - leftSide) / 2.0 + leftSide;
    CGFloat mid2 = (self.view.width - kLeftViewLitWidth) / 2.0 + leftSide + kLeftViewLitWidth;
    if (self.leftView.right < mid1) {
        [UIView animateWithDuration:0.3 animations:^{
            self.leftView.right = leftSide;
            self.bkView.alpha = 0;
        } completion:^(BOOL finished) {
            self.view.userInteractionEnabled = YES;
            [self.view sendSubviewToBack:self.bkView];
            self.scrollStep = LeftTableScrollStepOne;
        }];
        
    }else if (self.leftView.right < mid2) {
        [UIView animateWithDuration:0.3 animations:^{
            self.leftView.left = 0;
            [self.view bringSubviewToFront:self.bkView];
            [self.view bringSubviewToFront:self.leftView];
            [self.view bringSubviewToFront:self.locationView];
            [self.view bringSubviewToFront:self.dropMenu];
            self.bkView.alpha = 1;
            self.leftView.width = kLeftViewLitWidth;
            self.tableView.width = self.leftView.width - leftSide;
        } completion:^(BOOL finished) {
            self.view.userInteractionEnabled = YES;
            self.rightButton.selected = NO;
            self.scrollStep = LeftTableScrollStepTwo;
            if (self.dropMenu.bottom != kBDTopHeight) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.dropMenu.bottom = kBDTopHeight;
//                    self.dropMenu.bottom = self.locationView.top;
                    self.tableView.top = self.dropMenu.bottom - kBDTopHeight;
                } completion:^(BOOL finished) {
                    
                }];
            }
        }];
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            self.leftView.width = kBDScreenWidth + leftSide;
            self.tableView.width = self.leftView.width - leftSide;
        } completion:^(BOOL finished) {
            self.view.userInteractionEnabled = YES;
            self.scrollStep = LeftTableScrollStepThree;
            self.rightButton.selected = YES;
            if (self.dropMenu.top != kBDTopHeight) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.dropMenu.top = kBDTopHeight;
//                    self.locationView.top = self.dropMenu.bottom;
                    self.tableView.top = self.dropMenu.bottom - kBDTopHeight;
                } completion:^(BOOL finished) {
                    
                }];
            }
        }];
    }
}

- (void)panGR:(UIPanGestureRecognizer *)pan{
    //当在第一阶段的时候直接移动，第三阶段直接变更宽度，第二阶段
    //点相对于上一个点的位置
    CGPoint moviePoint = [pan translationInView:pan.view];
    
    if (self.scrollStep == LeftTableScrollStepTwo && moviePoint.x < 0) {
        self.scrollStep = LeftTableScrollStepOneHalf;
    }else if (self.scrollStep == LeftTableScrollStepTwo && moviePoint.x > 0) {
        self.scrollStep = LeftTableScrollStepTwoHalf;
    }
    
    if (self.scrollStep == LeftTableScrollStepOne || self.scrollStep == LeftTableScrollStepOneHalf) {
        
        CGFloat curRight = self.leftView.right += moviePoint.x;
        curRight = curRight < leftSide ? leftSide : curRight;
        curRight = curRight > kLeftViewLitWidth ? kLeftViewLitWidth : curRight;
        self.leftView.right = curRight;
    }else if (self.scrollStep == LeftTableScrollStepThree || self.scrollStep == LeftTableScrollStepTwoHalf) {
        CGFloat curWidth = self.leftView.width += moviePoint.x;
        curWidth = curWidth < kLeftViewLitWidth ? kLeftViewLitWidth : curWidth;
        curWidth = curWidth > kBDScreenWidth + leftSide ? kBDScreenWidth + leftSide : curWidth;
        self.leftView.width = curWidth;
        self.tableView.width = self.leftView.width - leftSide;
    }
    
    //每次都需要复位
    [pan setTranslation:CGPointZero inView:self.leftView];
    //松开手指时判断滑动趋势让其归位
    
    if (self.dropMenu.bottom != kBDTopHeight) {
        [self.dropMenu shouqiTableView];
    }
    
    if (pan.state == UIGestureRecognizerStateEnded) {
        if (pan.view.right == leftSide) {
            self.scrollStep = LeftTableScrollStepOne;
        }else if (pan.view.right == kLeftViewLitWidth) {
            self.scrollStep = LeftTableScrollStepTwo;
            self.rightButton.selected = NO;
            if (self.dropMenu.bottom != kBDTopHeight) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.dropMenu.bottom = kBDTopHeight;
//                    self.dropMenu.bottom = self.locationView.top;
                    self.tableView.top = self.dropMenu.bottom - kBDTopHeight;
                } completion:^(BOOL finished) {
                    
                }];
            }
        }else if (pan.view.right == kBDScreenWidth + leftSide) {
            self.scrollStep = LeftTableScrollStepThree;
            self.rightButton.selected = YES;
            if (self.dropMenu.top != kBDTopHeight) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.dropMenu.top = kBDTopHeight;
//                    self.locationView.top = self.dropMenu.bottom;
                    self.tableView.top = self.dropMenu.bottom - kBDTopHeight;
                } completion:^(BOOL finished) {
                    
                }];
            }
        }else{
            [self endScroll];
        }
    }
}

#pragma mark ------------------------高德定位代理------------------------------
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location{
    // BDLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
}

#pragma mark ------------------------高德地图代理------------------------------

- (void)mapView:(MAMapView *)mapView mapDidZoomByUser:(BOOL)wasUserAction {
    if (wasUserAction == YES) {
            self.startPage = @"1";
            [self requestDatasource];
    }
}

- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction{
    if (wasUserAction == YES) {
        self.startPage = @"1";
        [self requestDatasource];
    }
}

/*
 @brief 根据anntation生成对应的View
 @param mapView 地图View
 @param annotation 指定的标注
 @return 生成的标注View
 */
- (MAAnnotationView*)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        BDDiscoverAnnotationView *annotationView = (BDDiscoverAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[BDDiscoverAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
        }
        annotationView.label.text = [NSString stringWithFormat:@"%lu",(unsigned long)[self.annotations indexOfObject:annotation] + 1];
        annotationView.canShowCallout               = YES;        //弹出小视图
        
        NSInteger index = [self.annotations indexOfObject:annotation];

        [[annotationView.button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (index < self.datasource.count) {
                BDDiscoverShopModel *targetShopModel = self.datasource[index];
                [CallExternalProcessBehavior routeNavigationWithLongitue:targetShopModel.longitude latitue:targetShopModel.latitude];
            }
        }];
        
        BDDiscoverShopModel *shopModel = self.datasource[index];
        annotationView.image = [UIImage imageNamed:[NSString stringWithFormat:@"annotation%zd", shopModel.type]];
        
        return annotationView;
    }
    
    return nil;
}

/*!
 @brief 当mapView新添加annotation views时调用此接口
 @param mapView 地图View
 @param views 新添加的annotation views
 */
- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    
}

/*!
 @brief 当选中一个annotation views时调用此接口
 @param mapView 地图View
 @param view 选中的annotation views
 */
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
    
}

/*!
 @brief 当取消选中一个annotation views时调用此接口
 @param mapView 地图View
 @param view 取消选中的annotation views
 */
- (void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view {
    
}

/*!
 @brief 标注view的accessory view(必须继承自UIControl)被点击时调用此接口
 @param mapView 地图View
 @param view callout所属的标注view
 @param control 对应的control
 */
- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
    
}

/**
 *  标注view的calloutview整体点击时调用此接口
 *
 *  @param mapView 地图的view
 *  @param view calloutView所属的annotationView
 */
- (void)mapView:(MAMapView *)mapView didAnnotationViewCalloutTapped:(MAAnnotationView *)view {
    NSInteger index = [self.annotations indexOfObject:view.annotation];
    BDShopInfoDeatilViewController *bussinessVC = [[BDShopInfoDeatilViewController alloc]init];
    bussinessVC.hidesBottomBarWhenPushed = YES;
    //商家id
    BDDiscoverShopModel *shopModel = self.datasource[index];
    bussinessVC.shopID = [NSString stringWithFormat:@"%zd", shopModel.shop_id];
    bussinessVC.title = shopModel.title;
    [self.navigationController pushViewController:bussinessVC animated:YES];
}

/*!
 @brief 拖动annotation view时view的状态变化，ios3.2以后支持
 @param mapView 地图View
 @param view annotation view
 @param newState 新状态
 @param oldState 旧状态
 */
- (void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view didChangeDragState:(MAAnnotationViewDragState)newState fromOldState:(MAAnnotationViewDragState)oldState {
    // BDLog(ASLocalizedString(@"拖动了地图"));
}

#pragma mark -----------------------tableView代理-------------------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cellID";
    BDDiscoverLeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[BDDiscoverLeftTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.datasource.count != 0) {
        BDDiscoverShopModel *shopModel = self.datasource[indexPath.row];
        [cell.coverImage sd_setImageWithURL:[NSURL URLWithString:shopModel.cover] placeholderImage:[UIImage imageNamed:@"shop_moren.jpg"]];
        cell.shopName.text = [NSString stringWithFormat:@"%zd.%@",indexPath.row + 1,shopModel.title];
        [cell.starView displayRating:shopModel.score];    //评分
//        [cell.starView displayRating:4];
        cell.EvaluateNum.text = [NSString stringWithFormat:ASLocalizedString(@"%zd人评价"), shopModel.commentCount];
        cell.yishouLabel.text = [NSString stringWithFormat:ASLocalizedString(@"已售%@"),shopModel.sales];
        cell.locationLabel.text = shopModel.address;                  //地址
        
        cell.tuiguangLabel.hidden = YES;
        if (shopModel.priority == BDShopPriorityModeSigning) {
            cell.shopName.textColor = [UIColor colorWithHexString:@"#ff7e00"];
        }else if (shopModel.priority == BDShopPriorityModePromote) {
            cell.shopName.textColor = [UIColor colorWithHexString:@"#f54336"];
            cell.tuiguangLabel.hidden = NO;
        }else{
            cell.shopName.textColor = KBDNameColor;
        }
        
        if (shopModel.hongbao) {
            cell.hongbaoImage.hidden = NO;
        }else{
            cell.hongbaoImage.hidden = YES;
        }
    
        NSString *distansStr = nil;
        if (shopModel.distance < 0.5) {
            distansStr = @"< 500m";
        }else if (shopModel.distance > 50) {
            distansStr = @"> 50 km";
        }else{
            distansStr = [NSString stringWithFormat:@"%.1f km",shopModel.distance];
        }
        cell.rangLabel.text = distansStr;  //与用户的距离
        
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BDShopInfoDeatilViewController *bussinessVC = [[BDShopInfoDeatilViewController alloc]init];
    bussinessVC.hidesBottomBarWhenPushed = YES;
    //商家id
    BDDiscoverShopModel *shopModel = self.datasource[indexPath.row];
    bussinessVC.shopID = [NSString stringWithFormat:@"%zd", shopModel.shop_id];
//    bussinessVC.distances = shopModel.distance;
    bussinessVC.title = shopModel.title;
    [self.navigationController pushViewController:bussinessVC animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 85;
}

#pragma mark -----------------------dropMenu代理-------------------------------
//标题个数
- (NSInteger)numberOfColumnsInMenu:(JSDropDownMenu *)menu{
    return 3;
}

//标题数据
- (NSString *)menu:(JSDropDownMenu *)menu titleForColumn:(NSInteger)column{
    NSString *title = nil;
    switch (column) {
        case 1: title = [[_data1[_currentData1LeftIndex] objectForKey:@"data"] objectAtIndex:_currentData1Index];
            break;
        case 0: title = _data2[_currentData2Index];
            break;
        case 2: title = _data3[_currentData3Index];
            break;
        default:
            return nil;
            break;
    }
    // BDLog(ASLocalizedString(@"当前的title：%@"), title);
    return title;
}

//具体列表显示的行数
- (NSInteger)menu:(JSDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column leftOrRight:(NSInteger)leftOrRight leftRow:(NSInteger)leftRow{
    if (column==1) {
        if (leftOrRight==0) {
            
            return _data1.count;
        } else{
            
            NSDictionary *menuDic = [_data1 objectAtIndex:leftRow];
            return [[menuDic objectForKey:@"data"] count];
        }
    } else if (column==0){
        
        return _data2.count;
        
    } else if (column==2){
        
        return _data3.count;
    }
    
    return 0;
}

//具体列表中显示什么
- (NSString *)menu:(JSDropDownMenu *)menu titleForRowAtIndexPath:(JSIndexPath *)indexPath{
    if (indexPath.column==1) {
        if (indexPath.leftOrRight==0) {
            NSDictionary *menuDic = [_data1 objectAtIndex:indexPath.row];
            return [menuDic objectForKey:@"title"];
        } else{
            NSInteger leftRow = indexPath.leftRow;
            NSDictionary *menuDic = [_data1 objectAtIndex:leftRow];
            return [[menuDic objectForKey:@"data"] objectAtIndex:indexPath.row];
        }
    } else if (indexPath.column==0) {
        
        return _data2[indexPath.row];
        
    } else {
        
        return _data3[indexPath.row];
    }
}

- (NSInteger)currentLeftSelectedRow:(NSInteger)column{
    if (column==1) {
        
        return _currentData1LeftIndex;
        
    }
    if (column==0) {
        
        return _currentData2Index;
    }
    
    return _currentData3Index;
}



- (void)menu:(JSDropDownMenu *)menu didSelectRowAtIndexPath:(JSIndexPath *)indexPath{
    BOOL menuNeedRefresh = NO;
    if (indexPath.column == 1) {
        //右边点击，只有当右边点击确定之后才会跟着改变
        if(indexPath.leftOrRight==1){
            if (_currentData1LeftIndex != indexPath.leftRow || _currentData1Index != indexPath.row) {
                menuNeedRefresh = YES;
            }
            _currentData1LeftIndex = indexPath.leftRow;
            _currentData1Index = indexPath.row;
        }
    } else if(indexPath.column == 0){
        if (_currentData2Index != indexPath.row) {
            menuNeedRefresh = YES;
        }
        _currentData2Index = indexPath.row;
        [[NSUserDefaults standardUserDefaults] setObject:_data2[_currentData2Index] forKey:@"shopAndPostType"];
    } else{
        if (_currentData3Index != indexPath.row) {
            menuNeedRefresh = YES;
        }
        _currentData3Index = indexPath.row;
    }
    
    if (menuNeedRefresh == YES) {
        self.startPage = @"1";
        [self requestDatasource];
    }
    
}

//是否需要右侧列表
- (BOOL)haveRightTableViewInColumn:(NSInteger)column{
    if (column == 1) {
        return YES;
    }
    return NO;
}

-(CGFloat)widthRatioOfLeftColumn:(NSInteger)column{
    if (column == 1) {
        return 0.5;
    }
    return 1;
}

- (UIView *)makeZoomPannelView{
    UIView *ret = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 42, 90)];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:ret.bounds];
    imageView.image = [UIImage imageNamed:@"jia_jian"];
    [ret addSubview:imageView];
    
    self.fangdaBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 42, 45)];
    [_fangdaBtn sizeToFit];
    
    self.suoxiaoBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 45, 42, 45)];
    [_suoxiaoBtn sizeToFit];
    
    [ret addSubview:_fangdaBtn];
    [ret addSubview:_suoxiaoBtn];
    
    return ret;
}

#pragma mark -----------------------lazy-------------------------------
- (UIView *)bkView{
    if (!_bkView) {
        self.bkView = [[UIView alloc] initWithFrame:self.view.bounds];
        _bkView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.1];
        [self.view addSubview:_bkView];
        
        UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(startScroll)];
        [_bkView addGestureRecognizer:tapGR];
    }
    return _bkView;
}

- (MAMapView *)mapView{
    if (!_mapView) {
        self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight - kBDTabBarHeight)];
//        _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _mapView.delegate = self;
        _mapView.centerCoordinate = CLLocationCoordinate2DMake(23.117055306224895, 113.2759952545166);
        _mapView.showsUserLocation = YES;
        _mapView.showsCompass = NO;
        _mapView.showsScale = NO;
        MAUserLocationRepresentation *locationRepresntation = [[MAUserLocationRepresentation alloc] init];
        locationRepresntation.showsAccuracyRing = YES;
        [_mapView updateUserLocationRepresentation:locationRepresntation];
        _mapView.zoomLevel = 14.2;
        _mapView.minZoomLevel = 5;
        _mapView.maxZoomLevel = 20;
        
    }
    return _mapView;
}

- (AMapLocationManager *)locationManager{
    if (!_locationManager) {
        self.locationManager = [[AMapLocationManager alloc] init];
        
        [_locationManager setDelegate:self];
        [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
        
        [self.locationManager setLocationTimeout:6];
        
        [self.locationManager setReGeocodeTimeout:3];
    }
    return _locationManager;
}


- (UIView *)leftView{
    if (!_leftView) {
        self.leftView = [[UIView alloc]initWithFrame:CGRectMake(-kLeftViewLitWidth, kBDTopHeight, kLeftViewLitWidth, kBDScreenHeight - kBDTopHeight - kBDTabBarHeight)];
        _leftView.backgroundColor = [UIColor clearColor];
        [_leftView insertSubview:self.tableView atIndex:0];
        
        UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGR:)];
        panGR.delegate = self;
        [_leftView addGestureRecognizer:panGR];
    
        [_leftView bringSubviewToFront:self.tableView];
    }
    return _leftView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.leftView.width - leftSide, kBDScreenHeight - kBDTopHeight - kBDTabBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        
        _tableView.layer.shadowOffset = CGSizeMake(0, 0);
        _tableView.layer.shadowColor = [UIColor blackColor].CGColor;
        _tableView.layer.shadowOpacity = 0.5;
        _tableView.layer.shadowRadius = 5;
        _tableView.clipsToBounds = NO;
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.startPage = @"1";
            [self requestDatasource];
        }];
        
    }
    return _tableView;
}

- (JSDropDownMenu *)dropMenu{
    if (!_dropMenu) {
        self.dropMenu = [[JSDropDownMenu alloc] initWithOrigin:CGPointMake(0, kBDTopHeight) Height:44 SuperViewBounds:self.view.bounds];
        _dropMenu.delegate = self;
        _dropMenu.dataSource = self;
    }
    return _dropMenu;
}

- (UIView *)locationView{
    if (!_locationView) {
        self.locationView = [[UIView alloc] initWithFrame:CGRectMake(0, self.dropMenu.bottom, kBDScreenWidth, 28)];
        _locationView.backgroundColor = [UIColor colorWithHexString:@"#f6f2e7"];
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor colorWithHexString:@"#808080"];
        label.text = ASLocalizedString(@"当前：中国广东省广州市天河区天河南二路");
        [label sizeToFit];
        label.centerY =_locationView.height / 2.0;
        label.left = 10;
        [_locationView addSubview:label];
    }
    return _locationView;
}

- (UIButton *)rightButton{
    if (!_rightButton) {
        self.rightButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 5, 30, 30)];
        [_rightButton setImage:[UIImage imageNamed:@"map"] forState:UIControlStateNormal];
        [_rightButton setImage:[UIImage imageNamed:@"liebiao"] forState:UIControlStateSelected];
        _rightButton.selected = NO;
    }
    return _rightButton;
}

- (UIButton *)gpsButton{
    if (!_gpsButton) {
        self.gpsButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        _gpsButton.backgroundColor = [UIColor whiteColor];
        _gpsButton.layer.cornerRadius = 4;
        
        [_gpsButton setImage:[UIImage imageNamed:@"dingwei"] forState:UIControlStateNormal];
        _gpsButton.left = 10;
        _gpsButton.bottom = self.mapView.bottom - 10;
    }
    return _gpsButton;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray array];
    }
    return _datasource;
}

- (NSMutableArray *)annotations{
    if (!_annotations) {
        self.annotations = [NSMutableArray array];
    }
    return _annotations;
}

//页面有多个手势时 需要遵循协议-> UIGestureRecognizerDelegate 以及实现协议中的方法
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
